/*
 * Cloud.cpp
 *
 *  Created on: 1 avr. 2009
 *      Author: CHETIER
 */

#include "Cloud.h"

Cloud::Cloud(const char *pCloudImageUrl, int pMaxY, int pMinY,
		double pVelocityMax, int pScreenWidth)
{
	_CloudImageUrl = pCloudImageUrl;
	_Ymax = pMaxY;
	_Ymin = pMinY;
	_screenWidth = pScreenWidth;

	_velocityMax = pVelocityMax;
}

Cloud::~Cloud()
{
	//Free surfaces
	if (_srf_sprite != NULL)
		SDL_FreeSurface(_srf_sprite), _srf_sprite = NULL;
}

int Cloud::initialize()
{
	cout << "  Initializing Cloud" << _CloudImageUrl << endl;
	SDL_Surface *srf_buffer = SDL_LoadBMP(_CloudImageUrl);
	if (srf_buffer == NULL)
	{
		cout << "Error while loading: " << _CloudImageUrl;
		return EXIT_FAILURE;
	}
	_srf_sprite = SDL_DisplayFormat(srf_buffer);
	SDL_FreeSurface(srf_buffer), srf_buffer = NULL;

	SDL_SetColorKey(_srf_sprite, SDL_SRCCOLORKEY, SDL_MapRGB(
			_srf_sprite->format, 255, 0, 255));
	SDL_SetAlpha(_srf_sprite, SDL_SRCALPHA | SDL_RLEACCEL, 200);

	initializeX();
	initializeY();
	initializeVelocity();

	return EXIT_SUCCESS;
}

void Cloud::initializeX()
{
	_xExact = (_screenWidth * (double) random()) / RAND_MAX;
	_x = (int) _xExact;
}

void Cloud::initializeY()
{
	_yExact = _Ymin + ((_Ymax - _Ymin) * (double) random()) / RAND_MAX;
	_y = (int) _yExact;
}

void Cloud::initializeVelocity()
{
	_velocity = (_velocityMax * (double) random()) / RAND_MAX;
}

int Cloud::think()
{
	if (_velocity > 0)
	{
		if (_xExact < _screenWidth + getWidth() / 2)
		{
			_xExact += _velocity;
		}
		else
		{
			//Loop
			_xExact = -getWidth();
			initializeY();
			initializeVelocity();
		}
	}
	else if (_velocity < 0)
	{
		if (_xExact < getWidth())
		{
			_xExact += _velocity;
		}
		else
		{
			//Loop
			_xExact = _screenWidth + getWidth();
			initializeY();
			initializeVelocity();
		}
	}

	_x = (int) _xExact;
	_y = (int) _yExact;

	return EXIT_SUCCESS;
}

